import 'dart:convert';
import 'dart:typed_data';

class Utils {

  /// Converts the byte array to HEX string.
  ///
  /// @param buffer the buffer.
  /// @return the HEX string.
  static String toHexString(Uint8List buffer){
    if (buffer == null || buffer.isEmpty) {
      return "";
    }
    String s = "";
    for (var e in buffer) {
     s += e.toRadixString(16).padLeft(2,'0');
    }

    return s.toUpperCase();
  }

  /// Converts the byte array to HEX string.
  ///
  /// @param buffer the buffer.
  /// @return the HEX string.
  static List<int> string2Utf8(String data){

    Utf8Codec utf8 = const Utf8Codec();
    var hex = utf8.encode(data);
    return hex;

  }

  /// Converts the byte array to HEX string.
  ///
  /// @param buffer the buffer.
  /// @return the HEX string.
  static Future<String> hex2Ascii() async{
    // 创建一个 AsciiCodec 对象
    AsciiCodec ac=const AsciiCodec();
    // 编码 将ascii字符串转换成UintList类型 无法编码中文 会报错
    Uint8List list=ac.encode("Hello Dart");
    // 解码流 即将Stram<List<int>>类型转换成ascii字符串
    return await ac.decodeStream(Stream.value(list)); // Hello Dart

  }

  Future<String> hex2Base64() async {
    AsciiCodec ac=new AsciiCodec();
    Uint8List list=await ac.encode("Hello Dart");

    // Base64Codec允许base64将字节编码为ASCII字符串，并将有效编码解码回字节,始终是4的倍数。
    Base64Codec bc=new Base64Codec();
    // 编码
    String str=bc.encode(list);

    return str;

  }
}

